package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sort"
)

func playDir(path1 string, serverAddr string) error {
	names := getFileList(path1)
	log1 := getLogFromDir(path1)

	var start int
	var pos int
	if log1 != nil {
		for start < len(names) {
			if names[start] == log1.Name {
				break
			} else {
				start++
			}
		}
		pos = log1.Pos
	}

	if start == len(names) {
		return fmt.Errorf("No such file: ", log1.Name)
	}

	for start < len(names) {
		println(names[start])
		err := playFile(filepath.Join(path1, names[start]), pos, serverAddr)
		if err != nil {
			log.Println("error at playFile:", names[start])
			return err
		}
		pos = 0
		start++
	}
	return nil
}

func getFileList(path1 string) []string {
	dir1, err := os.Open(path1)
	if err != nil {
		return nil
	}
	defer dir1.Close()
	fds, err := dir1.Readdir(-1)
	if err != nil {
		return nil
	}
	var names = []string{}
	for _, fd := range fds {
		if fd.IsDir() {
			continue
		}
		names = append(names, fd.Name())
	}
	sort.Strings(names)
	return names
}
